package org.meteorshower.system_depart.service.impl;

import org.meteorshower.cms_common.exception.*;
import org.meteorshower.system_depart.config.RedisCache;
import org.meteorshower.system_depart.dao.IRole;
import org.meteorshower.system_depart.entity.Role;
import org.meteorshower.system_depart.service.RoleServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleServiceInter {

    @Autowired
    private IRole roleDao;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Role getById(Integer id) throws ServiceException, ResultNullPointException, ParameterNullPointException {
        if (id == null|| id.toString().isEmpty()){
            throw new ParameterNullPointException("参数为空");
        }
        AtomicReference<Role> role = new AtomicReference<>();
        //TODO：查询Redis有没有内容，有则直接返回
         if (redisCache.hasKey( "roleList")){
             redisCache.getCacheList( "roleList").forEach(r ->{
                 if (Objects.equals(((Role) r).getRoleId(), id)) {
                     role.set((Role) r);
                 }
             });
         }
        if ( role.get() != null){
            return role.get();
        }
        try{
            role.set(roleDao.getById(id));
        }catch (Exception e){
            throw new ServiceException("获取角色信息失败", e);
        }
        if (role.get() != null) {
            return role.get();
        }else{
            throw new ResultNullPointException("结果集为空");
        }

    }

    @Override
    public Role getByName(String name) throws ServiceException, ParameterNullPointException, ResultNullPointException {
        if (name == null|| name.isEmpty()){
            throw new ParameterNullPointException("参数为空");
        }
        AtomicReference<Role> role = new AtomicReference<>();
        //TODO：查询Redis有没有内容，有则直接返回
         if (redisCache.hasKey( "roleList")){
             redisCache.getCacheList( "roleList").forEach(r ->{
                 if (Objects.equals(((Role) r).getName(), name)) {
                     role.set((Role) r);
                 }
             });
        }
        if ( role.get() != null){
            return role.get();
        }
        try{
            role.set(roleDao.getByName(name));
        }catch (Exception e){
            throw new ServiceException("获取角色信息失败",e);
        }
        if (role.get() != null) {
            return role.get();
        }else{
            throw new ResultNullPointException("结果集为空");
        }
    }

    @Override
    public List<Role> getAll() throws ServiceException, ResultNullPointException {
        AtomicReference<List<Role>> roles = new AtomicReference<>();
        try{
            roles.set(roleDao.getAll());
        }catch (Exception e){
            throw new ServiceException("获取角色列表失败",e);
        }
        if (roles.get()!=null&& !roles.get().isEmpty()){
            //TODO:存入Redis
            redisCache.setCacheList( "roleList",roles.get());
            redisCache.expire( "roleList", 5, TimeUnit.MINUTES);
            return roles.get();
        }else{
            throw new ResultNullPointException("结果集为空");
        }

    }

    @Override
    public Integer insert(Role role) throws ServiceException, ParameterNullPointException, RecordExitException {
        if (role == null) {
             throw new ParameterNullPointException("参数为空");
        }
        role.setName( FormatName(role.getName()));
        if (redisCache.hasKey( "roleList")){
             redisCache.getCacheList( "roleList").forEach(r ->{
                 if (Objects.equals(((Role) r).getName(), role.getName())) {
                     role.setRoleId(((Role) r).getRoleId());
                 }
             });
        }
        if ( role.getRoleId() != null){
            return 1;
        }else{
            if ( roleDao.getByName(role.getName()) != null){
                throw new RecordExitException("该角色已存在");
            }
            try{

                if (roleDao.insert(role) > 0){
                    return 1;
                }else{
                    return 0;
                }
            }catch (Exception e){
                throw new ServiceException("添加角色失败",e);
            }
        }
    }

    @Override
    public Integer update(Role role) throws ServiceException, ParameterNullPointException, UnknownRecordException {
        if (role == null) {
            throw new ParameterNullPointException("参数为空");
        }
         role.setName( FormatName(role.getName()));
        if (roleDao.getById(role.getRoleId())==null){
             throw new UnknownRecordException("该角色不存在");
        }
         try{
            if (roleDao.update(role) > 0){
                return 1;
            }else{
                return 0;
            }
        }catch (Exception e){
            throw new ServiceException("更新角色失败",e);
        }
    }

    @Override
    public Integer deleteById(Integer id) throws ServiceException, ParameterNullPointException, UnknownRecordException {
        if (id == null) {
            throw new ParameterNullPointException("参数为空");
        }
        if (roleDao.getById( id)==null){
             throw new UnknownRecordException("该角色不存在");
        }
        try{
            if (roleDao.deleteById(id) > 0){
                return 1;
            }else{
                return 0;
            }
        }catch (Exception e){
            throw new ServiceException("删除角色失败",e);
        }
    }

    private String FormatName (String name){
        if (name == null|| name.isEmpty()){
            return "";
        }
        if (!name.toUpperCase().contains("ROLE_")){
            name = "ROLE_"+name;
        }
        return name.toUpperCase();
    }
}
